package org.itboys.mobile.service.mongo.mobile;

import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dto.SundayCountDto;
import org.itboys.mobile.dto.SundayCountProductDto;
import org.itboys.mobile.entity.mongo.SundayCart;
import org.itboys.mobile.entity.mysql.product.SundayProduct;
import org.itboys.mobile.service.mysql.mobile.product.SundayMobileProductService;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：圣代_购物车_service_移动端
 */
@Service
public class SundayMobileCartService extends BaseMongoService<SundayCart> {
    @Autowired
    private SundayMobileProductService productService;
    @Autowired
    private ResourceHolder resourceHolder;
    @Resource(name = "mobileDs")
    private MongoDataSource mobileDataSource;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return mobileDataSource;
    }
    @Override
    protected Class<SundayCart> getEntityClass() {
        return SundayCart.class;
    }




    /**
     * 新增购物车（不支持批量新增）。
     * @param memberId
     * @param productId
     * @param num
     * @param cartType
     * @return
     */
    public  List<Long> addCart(Long memberId,Long productId,Integer num,Integer cartType){
        List<Long> cartIds = new ArrayList<>();

        //如果是立即购买加入购物车，先删除原来购物车中立即购买加入的数据
        if(cartType== SundayCommonConstants.cart_type_buy_now){
            deleteCart(null,memberId, SundayCommonConstants.cart_type_buy_now);
        }
        //原来已经存在的数据
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("memberId",memberId);
        param.put("isDeleted",0);
        param.put("cartType",cartType);
        param.put("productId",productId);
        List<SundayCart> oldCarts=super.list(param);
        if(ListUtil.isNotNull(oldCarts)){
            super.update(oldCarts.get(0).getId(),"num",num+oldCarts.get(0).getNum());
            cartIds.add(oldCarts.get(0).getId());
        }else{
           SundayCart cart= new SundayCart(memberId, productId, num,cartType);
           super.save(cart);
            cartIds.add(cart.getId());
        }
        return cartIds;

    }

    /**
     * 修改数量
     * @param memberId
     * @param cartId
     * @param num
     */
    public void updateCart(Long memberId ,Long cartId ,Integer num){
        super.update(cartId,"num",num);
    }

    /**
     * 删除购物车，支持批量删除
     * @param cartIds
     * @param memberId
     * @param cartType
     */
    public void deleteCart(List<Long> cartIds ,Long memberId,Integer cartType){
        Map<String,Object> param = new HashMap<String,Object>();
        if(ListUtil.isNotNull(cartIds)){
            param.put("id in",cartIds);
        }
        param.put("memberId",memberId);
        param.put("isDeleted",0);
        if(cartType!=null){
            param.put("cartType",cartType);
        }
        super.delete(param);
    }


    /**
     * 获取购物车。不分页。
     * @param memberId
     * @param cartIds 结算/生成订单时传入此参数/手机端合计购物车商品价格（如系统含有满减，x元任选等促销手段）
     * @param cartType 1,通过购物车加入的；2，通过立即购买加入的
     * @return
     */
    public SundayCountDto getCart(Long memberId, List<Long> cartIds, Integer cartType){
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("memberId",memberId);
        param.put("isDeleted",0);
        if(ListUtil.isNotNull(cartIds)){
            param.put("id in",cartIds);
        }
        if(cartType!=null){
            param.put("cartType",cartType);
        }


        List<SundayCart> carts = super.list(param);
        //购物车外层数据。总价
        SundayCountDto countDto = new SundayCountDto();
        countDto.setTotalAmount(new BigDecimal("0"));
        countDto.setPayAmount(new BigDecimal("0"));
        countDto.setMemberId(memberId);
        if(ListUtil.isNull(carts))return countDto;
        //对应的商品数据
        List<Long> productIds = new ArrayList<Long>();//商品集合ID

        for(SundayCart cart:carts){
            productIds.add(cart.getProductId());
        }
        param.clear();
        param.put("ids",productIds);
        Double totalAmount = 0.00;
        Double payAmount=0.00;
        String imageRoot = resourceHolder.getStringValue("imgRoot");
        //商品信息
        List<SundayProduct> products = productService.select(param);
        //结算商品信息
        List<SundayCountProductDto>  countProductDtos= new ArrayList<>();
        for(SundayCart cart:carts){
            SundayCountProductDto productDto = new SundayCountProductDto();
            productDto.setId(cart.getProductId());
            productDto.setCartId(cart.getId());
            productDto.setNum(cart.getNum());

            //匹配商品基本信息
            for(SundayProduct product:products){
                if(cart.getProductId().longValue()==product.getId()){
                    productDto.setPrice(product.getPrice());
                    productDto.setName(product.getName());
                    productDto.setNumber(product.getNumber());
                    productDto.setPrice(product.getPrice());
                    productDto.setImage(imageRoot+product.getImage());
                    productDto.setStandard(product.getStandard());
                    productDto.setStatus(product.getStatus());
                    productDto.setSaleNumber(product.getSaleNumber());
                    break;
                }
            }
            countProductDtos.add(productDto);
            //计算应付和实付
           // logger.info("count-product-productId="+productDto.getId()+"-carId="+productDto.getCartId()+"-=price"+productDto.getPrice()+"-num"+ productDto.getNum());
            totalAmount+=productDto.getPrice().doubleValue()*productDto.getNum();
            payAmount+=productDto.getPrice().doubleValue()*productDto.getNum();
        }

        countDto.setProducts(countProductDtos);
        countDto.setTotalAmount(new BigDecimal(totalAmount).setScale(2,BigDecimal.ROUND_HALF_UP));
        countDto.setPayAmount(new BigDecimal(payAmount).setScale(2,BigDecimal.ROUND_HALF_UP));
        return countDto;
    }




}
